# -*- coding:utf-8 -*-
# business/common_func.py

from sanic.log import logger
from sqlalchemy import select

from model.models import (
    AppUser,
    AppSystem,
    AppSystemOwnermMap,
    AppSystemDeployMannerMap,
    BusinessChain,
    DeployManner
)
from utils.constants import OWNER_ROLE_MAPPING


async def get_busi_chain_by_busi_scenario_id(session, busi_scenario_id):
    """
    根据业务场景ID查询业务链中的应用系统
    """
    try:
        busi_chains_info = {}
        busi_chain_list = []
        async with session.begin():
            query_busi_chain = select(
                BusinessChain.chain_uuid,
                BusinessChain.sys_id,
                BusinessChain.sys_sn,
                AppSystem.app_system_id,
                AppSystem.sys_name
            ).outerjoin(
                AppSystem, AppSystem.sys_id == BusinessChain.sys_id
            ).where(
                BusinessChain.business_scenario_id == busi_scenario_id
            )
            result = await session.execute(query_busi_chain)
            rows = result.all()
            # fields = result.keys()
            # busi_chain_list = [dict(zip(fields, row)) for row in rows]
            busi_chain_list = [row._asdict() for row in rows]

        for bc_info in busi_chain_list:
            chain_uuid = bc_info.pop('chain_uuid')
            if not busi_chains_info.get(chain_uuid):
                busi_chains_info[chain_uuid] = []
            busi_chains_info[chain_uuid].append(bc_info)
        # 根据 sys_sn 排序
        for chain_uuid in busi_chains_info:
            busi_chains_info[chain_uuid].sort(key=lambda x: x['sys_sn'])
        logger.debug(f"get business_chains info by busi_scenario_id {busi_scenario_id}, res: {busi_chains_info}")

    except Exception as ex:
        logger.exception(ex)
        raise Exception("根据业务场景ID查询业务链中的应用系统异常: %s" % str(ex))
    return busi_chains_info


async def get_app_system_owner(session, app_system_id):
    """
    根据应用系统ID查询相关负责人
    """
    try:
        app_sys_owner_list = []
        async with session.begin():
            query_sys_owner = select(
                AppSystemOwnermMap.owner_role,
                AppSystemOwnermMap.app_user_id,
                AppUser.user_name
            ).outerjoin(
                AppUser, AppUser.app_user_id == AppSystemOwnermMap.app_user_id
            ).where(
                AppSystemOwnermMap.app_system_id == app_system_id
            )
            result = await session.execute(query_sys_owner)
            rows = result.all()
            app_sys_owner_list = [row._asdict() for row in rows]

        app_sys_owner_info = {}
        for aso in app_sys_owner_list:
            owner_role = aso.pop('owner_role')
            owner_role_alias = OWNER_ROLE_MAPPING.get(owner_role, "未知角色")
            if not app_sys_owner_info.get(owner_role_alias):
                app_sys_owner_info[owner_role_alias] = []
            app_sys_owner_info[owner_role_alias].append(aso['user_name'])

        logger.debug(f"get app_system_owner info by app_system_id {app_system_id}, res: {app_sys_owner_info}")

    except Exception as ex:
        logger.exception(ex)
        raise Exception("根据应用系统ID查询相关负责人异常: %s" % str(ex))
    return app_sys_owner_info


async def get_app_system_deploy_manner(session, app_system_id):
    """
    根据应用系统ID查询部署方式
    """
    try:
        deploy_manner_list = []
        async with session.begin():
            query_deploy_manner = select(
                AppSystemDeployMannerMap.app_system_id,
                DeployManner.alias_name
            ).join(
                DeployManner,
                DeployManner.deploy_manner_id == AppSystemDeployMannerMap.deploy_manner_id
            ).where(
                AppSystemDeployMannerMap.app_system_id == app_system_id
            )
            result = await session.execute(query_deploy_manner)
            # deploy_manner_list = result.scalars().all()
            rows = result.all()
            deploy_manner_list = [row[1] for row in rows]

        logger.debug(f"get app_system_deploy_manner info by app_system_id {app_system_id}, res: {deploy_manner_list}")

    except Exception as ex:
        logger.exception(ex)
        raise Exception("根据应用系统ID查询部署方式异常: %s" % str(ex))
    return deploy_manner_list
